<template>
  <div>
    <div class="email-customer" v-show="isEnd">
      <div class="make">
        <div class="left">
          <el-select v-model="targetRemove" @change="toRemove" size="mini" placeholder="移动到">
            <el-option value="" label="移动到" hidden></el-option>
            <el-option label="垃圾邮件" value="5"></el-option>
            <el-option label="归档文件" value="7"></el-option>
          </el-select>
          <el-button @click="emptyEmail()" size="small">彻底删除</el-button>
        </div>
        <!-- 固定图标-->
        <div style="display: flex;align-items: center">
          <el-input placeholder="输入邮件信息搜索" v-model="searchContent" class="input-with-select" style="width: 230px"
                    size="mini" @keyup.enter.native="handleCurrent(1)">
            <el-button slot="append" icon="el-icon-search" @click="handleCurrent(1)"></el-button>
          </el-input>
        </div>
      </div>
      <!-- 列表数据展示-->
      <div class="list-table">
        <!--表头-->
        <table class="table-title">
          <tbody>
          <tr>
            <td style="padding-left: 14px;width: 14px">
              <el-checkbox v-model="checked" @change="selectAll"></el-checkbox>
            </td>
            <td style="width: 30px;text-align: center;"><span class="el-icon-message"></span></td>
            <td width="150px">收件人邮箱</td>
            <td width="140px">发件人昵称</td>
            <td style="max-width: 360px"><span>邮件主题</span></td>
            <td width="200px">邮件标签</td>
            <td width="150px">邮件时间</td>
            <td width="60px">操作</td>
          </tr>
          </tbody>
        </table>
        <!--内容 -->
        <div class="detail" :style="{maxHeight:$height-235+'px'}">
          <div v-for="item,i in data" :key="i">
            <h1 class="title-table" v-show="item.total>0">{{item.title}}({{item.total}})</h1>
            <table class="table-detail">
              <tbody>
              <tr v-for="itemSon,i in item.list" :key="i" :class="{'active':parseInt(itemSon.readStatus)==1}">
                <td style="padding-left: 14px;width: 14px">
                  <input type="checkbox" v-model="tEmailInfoIds" :value="itemSon.temailInfoId">
                </td>
                <td style="width: 30px;text-align: center">
                  <!--是否建档-->
                  <img v-if="itemSon.emailCustomerVO.type ==0" title="陌生人"
                       src="../../../../public/img/email/icon/icon-people.png" class="delivery-img"
                       alt="陌生人">
                  <img v-else-if="itemSon.emailCustomerVO.type ==4" title="公海客户"
                       src="../../../../public/img/email/icon/icon-common.png" class="delivery-img"
                       alt="公海客户">
                  <img v-else-if="itemSon.emailCustomerVO.type ==2"  title="同事建档客户"
                       src="../../../../public/img/email/icon/icon-worker.png" class="delivery-img"
                       alt="同事建档客户">
                  <img v-else-if="itemSon.emailCustomerVO.type ==3"  title="共享客户"
                       src="../../../../public/img/email/icon/icon-share.png" class="delivery-img"
                       alt="共享客户">
                  <img v-else title="建档客户" src="../../../../public/img/email/icon/icon-customer.png"
                       class="delivery-img" alt="建档客户">
                </td>
                <td width="150px" :title="itemSon.addresseeEmail" @click="toDetail(itemSon)">
                  <span style="width: 140px;padding-right: 10px" class="more">{{itemSon.addresseeEmail}}</span>
                </td>
                <td width="140px" :title="itemSon.senderNickName" @click="toDetail(itemSon)">
                  <span style="width: 130px;padding-right: 10px" class="more">{{itemSon.senderNickName}}</span>
                </td>
                <td :title="itemSon.emailSubject" @click="toDetail(itemSon)">
                  <span class="more" style="max-width: 360px">
                    <!--1.紧急图标 -->
                     <img v-if="parseInt(itemSon.emaileDelivery)==2" title="紧急邮件"
                          src="../../../../public/img/email/icon/icon-emps.png" class="delivery-img" alt="紧急邮件">
                    <!--2.是否回复-->
                      <img v-if="parseInt(itemSon.emailReply)==1" title="已回复"
                           src="../../../../public/img/email/icon/icon-replay.png" alt="" class="delivery-img">
                    {{itemSon.emailSubject}}
                  </span>
                </td>
                <td width="200px">
                  <el-tag closable
                          v-for="itemElse in itemSon.emailLabelList"
                          :key="itemElse.labelName" :color="itemElse.labelColor"
                          @close="handleClose(itemElse.temailLabelId)">
                    {{itemElse.labelName}}
                  </el-tag>
                </td>
                <td width="150px" :title="itemSon.sendTime" @click="toDetail(itemSon)">
                  <span style="width: 150px"class="time">{{itemSon.sendTime}}</span>
                </td>
                <td width="60px">
                  <span class="el-icon-delete-solid icon" title="删除邮件" style="color: #666666b5 !important"
                        @click="delEmail(itemSon.temailInfoId)"></span>
                  <span class="el-icon-paperclip icon operation_icon" title="邮件附件"
                        v-show="itemSon.attachmentNumber>0">
                     </span>
                </td>
              </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
      <div class="empty" v-show="total==0">
        <img src="../../../../public/img/empty.png" alt="">
      </div>
      <el-pagination class="fixed"
                     background align="right"
                     @current-change="handleCurrent"
                     @size-change="handleSizeChange"
                     :current-page="currentPage"
                     :page-size="size"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
      <DocDialog ref="docDialog" @dealFoldID="dealFoldID"></DocDialog>
    </div>
  </div>
</template>
<script>
    import {mapState} from 'vuex'
    import {getHour, getNextDate, getDate, getNext, getToady, getYesterday, getNowWeek, getNowMonth,getTimeEmailList} from "@/util/util"
    import {getRead} from "@/api/mail/write"
    import {delEmail, emptyEmail, removeEmail, delLabel} from "@/api/mail/make"
    import {queryEmailTypeList} from "@/api/mail/customer/slider"
    import DocDialog from "@/components/mail/dialog/DocDialog"

    export default {
        name: "EmailList",
        components: {DocDialog},
        data() {
            return {
                isFixed: 0,
                theEmail: '',
                total: 0,
                currentPage: 1,
                showHeader: false,
                checked: false,
                searchContent: '',
                data: [],
                list: [],
                size: 20,
                targetLabel: '',
                targetLabelElse: ['-4'],
                targetRemove: '',
                tEmailInfoIds: [],//所选邮件列表
                dialogTime: false,
                emailList: [],
                targetTime: '',
                todayTime: '',
                nextWeek: '',
                nextTime: '',
                userId: '',
                nextEmail: '',
                pickerOptions: {
                    disabledDate: time => {
                        return time.getTime() < Date.now() - 8.64e7
                    }
                },
                listAll: [],
                archiveFolderId: '',
                //新增
                moveArchiveFolderId: '',
                emailSubject: '',
                showLoading: false,
                isEnd:false
            }
        },
        computed: {
            ...mapState(['common']),
        },
        created() {
            this.currentPage = this.common.emailPage;
            this.size = this.common.emailPageSize;
            this.bus.$on('refreshEmailGet', () => {
                this.getData();
            })
        },
        mounted() {
            this.theEmail = this.common.currentEmail;
            this.getData();
            this.todayTime = getHour();
            this.nextWeek = getNextDate();
            this.bus.$on('getEmail', (params) => {
                if (params) {
                    this.userId = params.userId;
                    this.nextEmail = params.email;
                    this.theEmail = params.theEmail;
                }
                this.getData();
            })
        },
        methods: {
            //已读
            getRead(temailInfoId) {
                getRead({temailInfoIds: [temailInfoId]}).then(res => {
                    this.dealResult(res, 1)
                })
            },
            //全选
            selectAll(val) {
                if (val) {//全选
                    this.tEmailInfoIds = [];
                    this.listAll.map(item => {
                        this.tEmailInfoIds.push(item.temailInfoId)
                    })
                } else {
                    this.tEmailInfoIds = [];
                }
            },
            handleSizeChange(val) {
                this.size = val;
                this.$store.commit('SET_EMAILPAGESIZE', this.size)
                this.handleCurrent(1)
            },
            handleCurrent(val) {
                this.checked = false;
                this.tEmailInfoIds = [];
                this.currentPage = val;
                this.$store.commit('SET_EMAILPAGE', this.currentPage)
                this.getData();
            },
            toWrite() {
                this.bus.$emit('refreshEmailChange', -1)
                this.$router.push('/mail/write/index')
            },
            //根据邮箱+类型获取对应的邮件列表数据
            getData() {
                let email;
                if (this.nextEmail) { //下属客户
                    email = this.nextEmail
                } else if (this.theEmail) {
                    email = this.theEmail
                } else {
                    email = this.common.currentEmail
                }
                let params = {
                    userId: this.userId,//下属客户查询邮件时候需要
                    labelId: this.common.labelID,
                    query: this.searchContent,
                    emailAddress: email,
                    current: this.currentPage,
                    size: this.size,
                    archiveFolderId: this.archiveFolderId,
                    fixed: this.isFixed
                }
                if (!this.common.labelID) {
                    params = Object.assign({}, params, {boxId: 4})
                }
                queryEmailTypeList(params).then(res => {
                    this.isEnd = true;
                    this.total = res.data.total;
                    const list = res.data.records;
                    this.listAll = list;
                    this.data = getTimeEmailList(list);
                })
            },
            //去除标记 单个
            handleClose(id) {
                delLabel(id).then(res => {
                    this.dealResult(res, 1)
                }).catch(err => {
                    console.log(err)
                });
            },
            //去详情页面
            toDetail(row) {
                sessionStorage.setItem("lastpath", this.$route.fullPath)
                this.$store.commit('SET_EMAILPAGE', this.currentPage)
                this.$store.commit('SET_EMAILPAGESIZE', this.size)
                let path = '/mail/common/detail';
                this.$router.push({
                    path: path,
                    query: {
                        id: row.temailInfoId
                    }
                })
            },
            //移动邮件
            toRemove(val) {
                if (!this.getSelectList()) {
                    this.targetRemove = '';
                    return;
                }
                if (val == '7') { //选择归档文件夹
                    this.$refs.docDialog.init();
                    this.targetRemove = '';
                } else {
                    this.moveEmail();
                }
            },
            dealFoldID(id) {
                this.moveArchiveFolderId = id;
                this.moveEmail();
            },
            moveEmail() {
                removeEmail({
                    boxId: this.moveArchiveFolderId ? 7 : this.targetRemove,
                    temailInfoIds: this.tEmailInfoIds,
                    archiveFolderId: this.moveArchiveFolderId
                }).then(res => {
                    this.dialogTime = false;
                    this.dealResult(res)
                }).catch(err => {
                    console.log(err)
                });
            },
            //彻底删除
            emptyEmail() {
                if (!this.getSelectList()) return;
                this.$confirm('彻底删除选中的邮件，确认?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "success"
                }).then(() => {
                    emptyEmail(this.tEmailInfoIds).then(res => {
                        this.dealResult(res)
                    }).catch(err => {
                        console.log(err)
                    });
                }).catch(() => {
                });
            },
            getTime() {
                switch (this.targetTime) {
                    case '1':
                        return getDate(0) + " " + this.todayTime + ":00";
                    case '2':
                        return getDate(1) + " 08:00:00";
                    case '3':
                        return getDate(2) + " 08:00:00";
                    case '4'://下周
                        let result;
                        if (this.nextWeek == '一') {
                            result = getNext(1)
                        } else if (this.nextWeek == '二') {
                            result = getNext(2)
                        } else if (this.nextWeek == '三') {
                            result = getNext(3)
                        }
                        return result + " 08:00:00";
                    case '稍后处理':
                        return this.nextTime;
                    default:
                        return
                }
            },
            //删除邮件
            delEmail(id) {
                let delArr = [];
                if (id) {
                    delArr.push(id)
                } else {
                    if (!this.getSelectList()) {
                        return;
                    } else {
                        delArr = this.tEmailInfoIds
                    }
                }
                if (delArr.length == 0) {
                    this.$message({
                        type: "success",
                        message: '请先选择要操作的邮件'
                    });
                    return;
                }
                this.$confirm('是否删除选中邮件?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "success"
                }).then(() => {
                    //获取选中的邮件列表
                    emptyEmail(delArr).then(res => {
                        this.dealResult(res)
                    }).catch(err => {
                        console.log(err)
                    })
                }).catch(() => {
                });
            },
            dealResult(res, index) {
                this.targetLabelElse = ['-4'];
                if (res.data.success) {
                    this.checked = false;
                    this.targetRemove = this.targetLabel = '';
                    this.tEmailInfoIds = [];
                    this.bus.$emit('refreshEmailNum')
                    this.$message({
                        type: "success",
                        message: res.data.msg
                    });
                    let page = index ? this.currentPage : 1;
                    this.handleCurrent(page);
                } else {
                    this.$message({
                        type: "success",
                        message: res.data.msg
                    });
                }
            },
            //获取选择的邮件
            getSelectList(param) {
                if (this.tEmailInfoIds.length === 0) {
                    this.$message({
                        type: "success",
                        message: '请先选择要操作的邮件'
                    });
                    return false
                } else {
                    return true;
                }
            },
            filterEmail(row){//itemSon.senderNickName}}|{{itemSon.addresseeEmail
                const name = row.senderNickName;
                const email = row.addresseeEmail;
                if(name==''){
                    return email.split("@")[0]+"|"+email
                }else{
                    return name+"|"+email
                }
            }
        },
        beforeDestroy() {
            this.bus.$off('getEmail');
            this.bus.$off('refreshEmailGet');
        }
    }
</script>

<style scoped lang="scss">
  @import "../../../styles/email";
</style>
